package nfwx.analytics;

import java.util.ArrayList;
import java.util.List;

/**
 * 采集参数,数组类型
 */

public class GrabArray extends GrabValue {
    protected List<GrabValue> _items;

    public GrabArray(boolean mustHasValue)
    {
        super(mustHasValue);
        _items = new ArrayList<>();
    }

    public final List<GrabValue> getValues()
    {
        return _items;
    }

    public GrabValue push(GrabValue v)
    {
        if (v._parent != null) throw new Error("Value to add alreay has a parent");
        v._parent = this;
        _items.add(v);
        if (v.getChanged()) {
            incChanged();
        }
        if (v.getHasValue()) {
            incHasValue();
        }
        return v;
    }

    public GrabValue push(String v)
    {
        GrabString gv = new GrabString(false);
        gv.setValue(v);
        return push(gv);
    }

    public GrabValue push(double v)
    {
        GrabNumber gv = new GrabNumber(false);
        gv.setValue(v);
        return push(gv);
    }

    public GrabValue push(boolean v)
    {
        GrabBoolean gv = new GrabBoolean(false);
        gv.setValue(v);
        return push(gv);
    }

    public int size()
    {
        return _items.size();
    }

    public GrabValue at(int i)
    {
        if (i < 0 || i >= _items.size()) {
            throw new Error("No value at index: " + i);
        }
        return _items.get(i);
    }

    public GrabArray set(int i, String v)
    {
        GrabValue gv = at(i);
        ((GrabString)gv).setValue(v);
        return this;
    }
    public GrabArray set(int i, double v)
    {
        GrabValue gv = at(i);
        ((GrabNumber)gv).setValue(v);
        return this;
    }
    public GrabArray set(int i, boolean v)
    {
        GrabValue gv = at(i);
        ((GrabBoolean)gv).setValue(v);
        return this;
    }

    public GrabValue shift()
    {
        if (_items.isEmpty()) return null;
        GrabValue gv = _items.remove(0);
        if (gv.getChanged()) {
            decChanged();
        }
        if (gv.getHasValue()) {
            decHasValue();
        }
        gv._parent = null;
        return gv;
    }

    public void clear()
    {
        while(shift() != null) ;
    }

    @Override
    public void resetChanged() {
        for(int i=0; i<_items.size(); ++i) {
            _items.get(i).resetChanged();
        }
    }

    @Override
    public void resetValue() {
        for(int i=0; i<_items.size(); ++i) {
            _items.get(i).resetValue();
        }
    }
}
